package phoeics.authoryserver.webservice.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import phoeics.authoryserver.util.JacksonUtil;
import phoeics.authoryserver.webservice.DTO.Card;
import phoeics.authoryserver.webservice.service.impl.TokenAuthenticationService;

public class LoginFilter extends AbstractAuthenticationProcessingFilter {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LoginFilter.class);
	
	public LoginFilter(String url, AuthenticationManager authManager){
		super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);
	}


	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		StringBuffer sb=new StringBuffer();
		request.getReader().lines().forEach(line->sb.append(line));
		logger.info(sb.toString());
		Card creds =JacksonUtil.readValue(sb.toString(), Card.class);
		return getAuthenticationManager().authenticate(
				new UsernamePasswordAuthenticationToken(creds.getUsername(),creds.getPassword())
				);
	}

	@Override
	protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth)
			throws IOException, ServletException {
		TokenAuthenticationService.addAuthentication(res, auth.getName());
	}

	/*@Override
	protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
			throws IOException, ServletException {
		response.setContentType("application/json");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getOutputStream().println(JSONResult.fillResultString(500, "Internal Server Error!!!", JSONObject.NULL));
	}*/
}
